﻿using System.Data.Linq;
using System.Linq;
using SeaBattle.Domain.Abstract;
using SeaBattle.Domain.Entities;

namespace SeaBattle.Domain.Concrete
{
    public class SqlPlayerRepository : IPlayerRepository
    {
        private readonly Table<Player> _playersTable;

        public SqlPlayerRepository(string connectionString)
        {
            _playersTable = (new DataContext(connectionString)).GetTable<Player>();
        }

        public IQueryable<Player> Players
        {
            get { return _playersTable.AsQueryable(); }
        }

        public Player CreateNewPlayer(string login, decimal balance)
        {
            var player = new Player(login, balance);
            SavePlayer(player);
            return _playersTable.Single(x => x.Login == player.Login);
        }

        public void SavePlayer(Player player)
        {
            if (player.Id == 0)
            {
                _playersTable.InsertOnSubmit(player);
            }
            else if (_playersTable.GetOriginalEntityState(player) == null)
            {
                _playersTable.Attach(player);
                _playersTable.Context.Refresh(RefreshMode.KeepCurrentValues, player);
            }

            _playersTable.Context.SubmitChanges();
        }
    }
}
